new Vue({
  el: '#app',
  data: {
    students: [],
    remainingStudents: [],
    calledStudents: [],
    result: '请导入学生名单',
    canStart: false,
    intervalId: null,
    autoStopTimer: null,
    countdownTimer: null,
    countdown: 0
  },
  methods: {
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const content = e.target.result;
          this.students = content.split('\n').filter(name => name.trim()!== '');
          this.remainingStudents = [...this.students];
          this.canStart = true;
          this.result = '学生名单已导入，点击开始点名';
          this.calledStudents = [];
        };
        reader.readAsText(file);
      }
    },
    startRollCall() {
      if (this.remainingStudents.length === 0) {
        this.remainingStudents = [...this.students];
        this.calledStudents = [];
      }
      this.canStart = false;
      this.intervalId = setInterval(() => {
        const randomIndex = Math.floor(Math.random() * this.remainingStudents.length);
        this.result = this.remainingStudents[randomIndex];
      }, 100);
      this.autoStopTimer = setTimeout(() => {
        if (this.intervalId) {
          clearInterval(this.intervalId);
          clearInterval(this.countdownTimer);
          this.processSelectedStudent();
          if (this.remainingStudents.length === 0) {
            this.result = '本轮点名结束，开始新的一轮点名';
            this.remainingStudents = [...this.students];
            this.calledStudents = [];
          } else {
            this.result = `已点到：${this.result}，剩余 ${this.remainingStudents.length} 名学生未点`;
          }
          this.canStart = true;
          this.countdown = 0;
        }
      }, 10000);

      this.countdown = 10;
      this.countdownTimer = setInterval(() => {
        this.countdown--;
        if (this.countdown < 0) {
          clearInterval(this.countdownTimer);
        }
      }, 1000);
    },
    stopRollCall() {
      clearInterval(this.intervalId);
      clearInterval(this.countdownTimer);
      clearTimeout(this.autoStopTimer);
      this.processSelectedStudent();
      if (this.remainingStudents.length === 0) {
        this.result = '本轮点名结束，开始新的一轮点名';
        this.remainingStudents = [...this.students];
        this.calledStudents = [];
      } else {
        this.result = `已点到：${this.result}，剩余 ${this.remainingStudents.length} 名学生未点`;
      }
      this.canStart = true;
      this.countdown = 0;
    },
    processSelectedStudent() {
      const selectedStudent = this.result;
      const index = this.remainingStudents.indexOf(selectedStudent);
      if (index!== -1) {
        this.remainingStudents.splice(index, 1);
        this.calledStudents.push(selectedStudent);
      }
    }
  }
});